﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Identity.Client;
using WpfApp3.Data;
using WpfApp3.Data_Operations;
using WpfApp3.Models;


namespace WpfApp3.ViewModels
{

    public class MainViewModel : INotifyPropertyChanged
    {
        public ICommand ModifyCommand { get; }
        public ICommand DeleteCommand { get; }
        public ICommand AddCommand { get; }
        public ICommand SelectModifyCommand { get; }
        public ICommand SearchCommand { get; }
        
        string filePath1 = @"File/persons.txt"; // 相对文件路径
        string filePath2 = @"File/persons.ini";
        private ObservableCollection<Person> _persons;
        public ObservableCollection<Person> Persons
        {
            get => _persons;
            set { _persons = value; OnPropertyChanged(); }
        }

       public SQLiteManager Sqlite { get; set; }
        

        /// <summary>
        /// 存放添加框内容
        /// </summary>
        /// <param name="InputText"></param>
        private string _inputText;
        public string InputText
        {
            get => _inputText;
            set
            {
                _inputText = value;
                OnPropertyChanged();
            }
        }
        /// <summary>
        /// 要查询的关键字
        /// </summary>
        /// <param name="SearchText"></param>
        private string _searchText;
        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                OnPropertyChanged();
                // 自动触发搜索
                SearchCommand.Execute(null);
            }
        }
        /// <summary>
        /// ListView中选定的person对象
        /// </summary>
        /// /// <param name="SelectedPerson"></param>
        private Person _selectedPerson;
        public Person SelectedPerson
        {
            get => _selectedPerson;
            set
            {
                _selectedPerson = value;
                OnPropertyChanged();


            }
        }
        /// <summary>
        /// 临时属性，用于在textbox展示SelectedPerson,
        /// </summary>
        private string _temporary;
        public SqlSugarManager _SqlSugar;
        public Fileoperations file1;
        public Fileoperation_ini file2;
        public Mysqloperations mysqloperations;
        public Sqlserver sqlServer { get; set; }

        public string Temporary
        {
            get => _temporary;
            set
            {
                _temporary = value;

                OnPropertyChanged();



            }
        }
        /// <summary>
        /// 查询结果集合
        /// </summary>
        /// <param name="FilteredPersons"></param>
        public ObservableCollection<Person> FilteredPersons { get; } = new ObservableCollection<Person>();

        


        public MainViewModel()
        {
            mysqloperations = new Mysqloperations();
            file1 = new Fileoperations(filePath1);
            file2 = new Fileoperation_ini(filePath2);
            SelectModifyCommand = new RelayCommand(SelectModifyMethod);
            DeleteCommand = new RelayCommand(DeleteMethod);
            AddCommand = new RelayCommand(AddMethod);
            SearchCommand = new RelayCommand(SearchMethod);
            ModifyCommand = new RelayCommand(ModifyMethod);
            Persons = new ObservableCollection<Person> { };
            Sqlite = new SQLiteManager { };
            _SqlSugar = new SqlSugarManager { };
            sqlServer = new Sqlserver();
            SyncDatabaseToFile();//从数据库同步到file1,file2文件
           //重新处理同步方案
            LoadPersonsFromDatabase();
            RefreshFilteredPersons();
        }
        // 将数据库数据同步到文件（覆盖现有文件内容）
        private void SyncDatabaseToFile()
        {
            try
            {
                file1.ClearAll();
                file2.ClearAll();
                var allPersons = Sqlite.GetAllPersons();
                

                foreach (var person in allPersons)
                {
                    string data = $"{person.Name} {person.Age} {person.Gender} " +
                                 $"{person.Characteristics} {person.Political} " +
                                 $"{person.Marital} {person.Remarks}";
                    file1.AddData(data);
                    file2.WritePerson(person);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"同步文件失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 从数据库加载人员信息
        /// </summary>
        /// /// <param name="LoadPersonsFromDatabase"></param>
        private void LoadPersonsFromDatabase()
        {
            var persons = Sqlite.GetAllPersons();
            foreach (var person in persons)
            {
                Persons.Add(person);
            }
        }
        /// <summary>
        /// 将字符串空格解析的方法，返回解析后的Person
        /// </summary>
        /// <param name="ParsePerson"></param>
        public Person ParsePerson(string input)
        {
            // 按空格分割字符串，允许转义空格 (\ )
            var parts = Regex.Split(input, @"(?<!\\)\s+")
                .Select(p => p.Trim().Replace(@"\ ", " "))
                .ToArray();

            string name = parts.Length > 0 ? parts[0] : string.Empty;
            int age = parts.Length > 1 ? (int.TryParse(parts[1], out int parsedAge) ? parsedAge : 0) : 0;
            string gender = parts.Length > 2 ? parts[2] : string.Empty;
            string characteristics = parts.Length > 3 ? parts[3] : string.Empty;
            string political = parts.Length > 4 ? parts[4] : string.Empty;
            string marital = parts.Length > 5 ? parts[5] : string.Empty;
            string remarks = parts.Length > 6 ? parts[6] : string.Empty;

            return new Person
            {
                Name = name,
                Age = age,
                Gender = gender,
                Characteristics = characteristics,
                Marital = marital,
                Political = political,
                Remarks = remarks
            };
        }
        //ui更新
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        /// <summary>
        /// 按空格解析InputText生成一个新的对象添加到Persons
        /// </summary>
        /// <param name="AddMethod"></param>
        private void AddMethod(object parameter)
        {
            if (string.IsNullOrWhiteSpace(InputText))
                return;

            try
            {
                // 解析字符串
                var person = ParsePerson(InputText);
                if (person != null)
                {
                    Persons.Add(person);
                    InputText = string.Empty; // 清空输入框
                                              // 将人员信息添加到数据库
                    Sqlite.AddPerson(person);
                    _SqlSugar.AddPerson(person);
                    file1.AddData($"{person.Name} {person.Age} {person.Gender} {person.Characteristics} {person.Political} {person.Marital} {person.Remarks}");
                    file2.WritePerson(person);
                    mysqloperations.AddPerson(person);
                    sqlServer.AddPerson(person);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }


        }
        /// <summary>
        /// 可扩展搜索方式，运行某一搜索方法
        /// </summary>
        /// <param name="SearchMethod"></param>
        private void SearchMethod(object parmerter)
        {
            RefreshFilteredPersons();
            //搜索方法
        }
        /// <summary>
        /// 搜索方式，对SearchText在Persons集合查询关键字，如有相等将Person对象添加到Filtered Persons
        /// </summary>
        ///  /// <param name="RefreshFilteredPersons"></param>
        private void RefreshFilteredPersons()
        {
            FilteredPersons.Clear();

            if (string.IsNullOrWhiteSpace(SearchText))
            {
                // 无搜索条件，显示全部
                foreach (var person in Persons)
                    FilteredPersons.Add(person);
            }
            else
            {
                // 按关键字搜索
                var lowerSearch = SearchText.ToLower();
                foreach (var person in Persons)
                {
                    if (person.Name.ToLower().Contains(lowerSearch) ||
                        person.Gender.ToLower().Contains(lowerSearch) ||
                        person.Characteristics.ToLower().Contains(lowerSearch) ||
                        person.Marital.ToLower().Contains(lowerSearch) ||
                        person.Political.ToLower().Contains(lowerSearch) ||
                        person.Remarks.ToLower().Contains(lowerSearch) ||
                        person.Age.ToString().Contains(lowerSearch))
                    {
                        FilteredPersons.Add(person);
                    }
                }
            }

        }
        /// <summary>
        /// 删除方法，查询与SelectedPerson.Name相等的Person对象在Persons中删除
        /// </summary>
        /// <param name="DeleteMethod"></param>
        private void DeleteMethod(object parameter)

        {


            if (SelectedPerson == null)
            {
                MessageBox.Show("请先选择一个人");
                return;
            }
            var personsToDelete = Persons.Where(p => p.Name == SelectedPerson?.Name).ToList();
            Debug.WriteLine($"删除前集合大小: {Persons.Count}");
            //Persons.Where(...)：在Persons列表中筛选出所有名字和Chosen_person相同的人
            //Chosen_person?.Name：?.是安全访问符，如果Chosen_person为空，直接返回null，不会报错
            // .ToList()：把筛选结果存到一个新的列表personsToDelete中
            MessageBox.Show($"找到 {personsToDelete.Count} 个匹配项");

            foreach (var person in personsToDelete)
            {
                Persons.Remove(person);
                file1.DeletePerson(person);
                file2.DeletePerson(person.Name);
                // 从数据库中删除人员信息
                _SqlSugar.DeletePerson(person.Name);
                Sqlite.DeletePerson(person.Name);
                mysqloperations.DeletePerson(person.Name);
                sqlServer.DeletePerson(person.Name);
            }

            //foreach (var person in personsToDelete)：遍历临时集合personsToDelete中的每一个元素。
            //Persons.Remove(person)：从原始集合Persons中删除当前遍历到的元素。
            MessageBox.Show($"删除后集合大小: {Persons.Count}");

        }
        /// <summary>
        /// 格式化SelectedPerosn,给Temporary
        /// </summary>
        /// <param name="SelectModifyMethod"></param>
        private void SelectModifyMethod(object parameter)
        {
            if (SelectedPerson != null)
            {
                Temporary = $"{SelectedPerson.Name} {SelectedPerson.Age} {SelectedPerson.Gender} {SelectedPerson.Characteristics} " +
                $"{SelectedPerson.Political} {SelectedPerson.Marital} {SelectedPerson.Remarks}";
            }
            MessageBox.Show($"未选中对象");
        }
        /// <summary>
        /// 修改方法下的重新添加方法
        /// 业务；将选中的Temporary通过空格解析ParsePerson(Temporary),生成一个新person对象添加回Persons
        /// </summary>
        /// <param name="Add"></param>
        private Person Add(object parameter)
        {
            var person = new Person();
            if (string.IsNullOrWhiteSpace(Temporary))
                return null;

            try
            {
                // 解析字符串
                 person = ParsePerson(Temporary);
                if (person != null)
                {
                    Persons.Add(person);
                   
                    Temporary = string.Empty; // 清空输入框
                                              // 将人员信息添加到数据库
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return person;

        }
        /// <summary>
        /// 修改方法，调用了Add，DeleteMethod
        /// </summary>
        /// <param name="ModifyMethod"></param>
        private void ModifyMethod(object parameter)
        {
            if (Temporary != null)
            {
                DeleteMethod(null);
                var p=Add(null);
                MessageBox.Show($"已修改");
                // 从临时字符串解析新的人员信息
                // 更新数据库中的人员信息
                Sqlite.UpdatePerson(p);
                _SqlSugar.UpdatePerson(p);
                file1.UpdatePerson(p);
                //file2.WritePerson(newPerson);//和txt操作不同的是第三方库IniParser提供的写入方式自动覆盖内容所以无需更新方法，
                //但测试时发现出现问题ModifyMethod在调用add时temporary被清空导致更新失败
                file2.WritePerson(p);
                mysqloperations.UpdatePerson(p);
                sqlServer.UpdatePerson(p);

            }
            MessageBox.Show($"未选中对象");
        }
    }
}
